<?php
    namespace app\controllers;
    use app\common\BaseController;
    use app\common\Utils;
    use app\models\diary;
    use app\models\Images;
    use Faker\Provider\Image;

    class DiaryController extends BaseController{
        public function actionAdd(){
            $postData = \Yii::$app->request->post();
            $diary = new diary();
            if (isset($postData['id'])){
                $diary = diary::find()->where(['id' => $postData['id']])->one();
            }
            $postData['time'] = strtotime($postData['time']);
            foreach ($postData as $key => $value){
                if ($key === 'imageList'){
                    $postData[$key] = implode(',', $value);
                }else{
                    if ($key !== 'time'){
                        $postData[$key] = Utils::encode($value);
                    }
                }
            }
            if ($diary->load($postData, '') && $diary->save()){
                $res = 0;
            }else{
                $res = $diary->errors;
            }
            return $this->result([], $res);
        }

        public function actionList(){
            $res = diary::find()->asArray()->all();
            foreach ($res as $key => $val){
                $res[$key]['whether'] = Utils::decode($res[$key]['whether']);
                $res[$key]['detail'] = Utils::decode($res[$key]['detail']);
                $res[$key]['time'] = date('Y-m-d', $res[$key]['time']);
            }
            return $this->result($res);
        }

        public function actionGetDiaryById(){
            $id = \Yii::$app->request->get('id', 0);
            $res = [];
            if ($id){
                $res = diary::find()->where(['id' => $id])->asArray()->one();
                $res['time'] = date('Y-m-d', $res['time']);
                $res['whether'] = Utils::decode($res['whether']);
                $res['detail'] = Utils::decode($res['detail']);
            }
            return $this->result($res);
        }

        public function actionAddImageRemark(){
            $postData = \Yii::$app->request->post();
            $imageObj = Images::find()->where(['id' => $postData['id']])->one();
            if ($imageObj){
                $imageObj->remark = $postData['remark'];
                if ($imageObj->save()){
                    return $this->result([]);
                }
            }
            return $this->result([], 1, '添加失败');
        }
    }